const dayjs = require('dayjs');
const BaseModel = require('./base_model');
/**
 * 项目申请模型
 * 处理项目申请数据和状态管理
 */

const cloudHelper = require('../helpers/cloud_helper.js');
const dataHelper = require('../helpers/data_helper.js');
const projectApplyTypes = require('./project_apply_types.js');
const projectSchema = require('./project_schema.js');

/**
 * 项目申请模型类
 */
class ProjectApplyModel extends BaseModel {
  constructor(data = {}) {
    super(data);
    // ... existing code ...
  }

  /**
   * 创建项目申请
   * @param {Object} data 项目申请数据
   * @returns {Promise<Object>} 处理结果
   */
  static async createApply(data) {
    if (!data || !data.applicationType) {
      console.error('[项目申请] 创建失败: 缺少申请类型');
      throw new Error('缺少申请类型');
    }

    try {
      // 处理申请类型
      const applyType = projectApplyTypes.getApplyTypeByProjectType(data.applicationType);
      
      // 设置申请基础数据
      const applyData = {
        ...data,
        APPLY_TYPE: applyType,
        APPLY_TYPE_NAME: projectApplyTypes.APPLY_TYPE_NAMES[applyType] || '其他类型',
        APPLY_STATUS: projectApplyTypes.PROJECT_STATUS.PLANNING,
        APPLY_STATUS_NAME: projectApplyTypes.PROJECT_STATUS_NAMES[projectApplyTypes.PROJECT_STATUS.PLANNING],
        APPLY_ACTIVE_STATUS: projectApplyTypes.ACTIVE_STATUS.PLAN_DRAFT,
        APPLY_ACTIVE_STATUS_NAME: projectApplyTypes.ACTIVE_STATUS_NAMES[projectApplyTypes.ACTIVE_STATUS.PLAN_DRAFT],
        APPLY_TIME: dayjs().valueOf(),
        APPLY_UPDATE_TIME: dayjs().valueOf()
      };
      
      // 调用云函数创建申请
      const result = await cloudHelper.callCloudData('project_apply/create', applyData, {
        pid: 'plm',
        PID: 'plm'
      });
      
      return result;
    } catch (e) {
      console.error('[项目申请模型] 创建申请失败:', e);
      throw e;
    }
  }
  
  /**
   * 提交项目申请审核
   * @param {String} applyId 申请ID
   * @returns {Promise<Object>} 处理结果
   */
  static async submitApply(applyId) {
    try {
      const result = await cloudHelper.callCloudData('project_apply/submit', {
        applyId
      }, {
        pid: 'plm',
        PID: 'plm'
      });
      
      return result;
    } catch (e) {
      console.error('[项目申请模型] 提交申请失败:', e);
      throw e;
    }
  }
  
  /**
   * 审批项目申请
   * @param {String} applyId 申请ID
   * @param {Boolean} isApprove 是否通过
   * @param {String} comment 审批意见
   * @returns {Promise<Object>} 处理结果
   */
  static async approveApply(applyId, isApprove, comment) {
    try {
      const result = await cloudHelper.callCloudData('project_apply/approve', {
        applyId,
        isApprove,
        comment
      }, {
        pid: 'plm',
        PID: 'plm'
      });
      
      return result;
    } catch (e) {
      console.error('[项目申请模型] 审批申请失败:', e);
      throw e;
    }
  }
  
  /**
   * 取消项目申请
   * @param {String} applyId 申请ID
   * @param {String} reason 取消原因
   * @returns {Promise<Object>} 处理结果
   */
  static async cancelApply(applyId, reason) {
    try {
      const result = await cloudHelper.callCloudData('project_apply/cancel', {
        applyId,
        reason
      }, {
        pid: 'plm',
        PID: 'plm'
      });
      
      return result;
    } catch (e) {
      console.error('[项目申请模型] 取消申请失败:', e);
      throw e;
    }
  }
  
  /**
   * 获取项目申请详情
   * @param {String} applyId 申请ID
   * @returns {Promise<Object>} 申请详情
   */
  static async getApplyDetail(applyId) {
    try {
      const result = await cloudHelper.callCloudData('project_apply/detail', {
        applyId
      }, {
        pid: 'plm',
        PID: 'plm'
      });
      
      return result.data;
    } catch (e) {
      console.error('[项目申请模型] 获取申请详情失败:', e);
      throw e;
    }
  }
  
  /**
   * 获取项目申请列表
   * @param {Object} params 查询参数
   * @returns {Promise<Object>} 申请列表
   */
  static async getApplyList(params = {}) {
    try {
      const result = await cloudHelper.callCloudData('project_apply/list', params, {
        pid: 'plm',
        PID: 'plm'
      });
      
      return result;
    } catch (e) {
      console.error('[项目申请模型] 获取申请列表失败:', e);
      throw e;
    }
  }
  
  /**
   * 更新项目申请
   * @param {Object} data 更新数据
   * @returns {Promise<Object>} 处理结果
   */
  static async updateApply(data) {
    if (!data || !data._id) {
      console.error('[项目申请] 更新失败: 缺少申请ID');
      throw new Error('缺少申请ID');
    }
    
    try {
      // 设置更新时间
      data.APPLY_UPDATE_TIME = dayjs().valueOf();
      
      // 调用云函数更新申请
      const result = await cloudHelper.callCloudData('project_apply/update', data, {
        pid: 'plm',
        PID: 'plm'
      });
      
      return result;
    } catch (e) {
      console.error('[项目申请模型] 更新申请失败:', e);
      throw e;
    }
  }
  
  /**
   * 触发项目状态流转事件
   * @param {String} applyId 申请ID
   * @param {String} eventCode 事件代码
   * @param {Object} eventData 事件数据
   * @returns {Promise<Object>} 处理结果
   */
  static async triggerEvent(applyId, eventCode, eventData = {}) {
    try {
      const result = await cloudHelper.callCloudData('project_apply/event', {
        applyId,
        eventCode,
        eventData
      }, {
        pid: 'plm',
        PID: 'plm'
      });
      
      return result;
    } catch (e) {
      console.error('[项目申请模型] 触发事件失败:', e);
      throw e;
    }
  }
  
  /**
   * 获取项目申请历史记录
   * @param {String} applyId 申请ID
   * @returns {Promise<Array>} 历史记录列表
   */
  static async getApplyHistory(applyId) {
    try {
      const result = await cloudHelper.callCloudData('project_apply/history', {
        applyId
      }, {
        pid: 'plm',
        PID: 'plm'
      });
      
      return result.data;
    } catch (e) {
      console.error('[项目申请模型] 获取历史记录失败:', e);
      throw e;
    }
  }
  
  /**
   * 上传项目申请相关文件
   * @param {String} applyId 申请ID
   * @param {String} fileType 文件类型
   * @param {Object} fileData 文件数据
   * @returns {Promise<Object>} 处理结果
   */
  static async uploadApplyFile(applyId, fileType, fileData) {
    try {
      // 先上传文件
      const cloudPath = `project_apply/${applyId}/${fileType}_${dayjs().valueOf()}${fileData.ext}`;
      const result = await cloudHelper.uploadFile(fileData.file, cloudPath, (progress) => {
        console.log('上传进度:', progress);
      });
      
      // 更新申请文件信息
      if (result && result.fileID) {
        await this.updateApplyFiles(applyId, fileType, {
          fileId: result.fileID,
          fileName: fileData.name,
          fileUrl: result.fileID,
          fileSize: fileData.size,
          fileType: fileData.type,
          uploadTime: dayjs().valueOf()
        });
      }
      
      return result;
    } catch (e) {
      console.error('[项目申请模型] 上传文件失败:', e);
      throw e;
    }
  }
  
  /**
   * 更新申请文件信息
   * @param {String} applyId 申请ID
   * @param {String} fileType 文件类型
   * @param {Object} fileInfo 文件信息
   * @returns {Promise<Object>} 处理结果
   */
  static async updateApplyFiles(applyId, fileType, fileInfo) {
    try {
      const result = await cloudHelper.callCloudData('project_apply/update_file', {
        applyId,
        fileType,
        fileInfo
      }, {
        pid: 'plm',
        PID: 'plm'
      });
      
      return result;
    } catch (e) {
      console.error('[项目申请模型] 更新文件信息失败:', e);
      throw e;
    }
  }
}

module.exports = ProjectApplyModel; 